package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.mysql.Admin;
import com.tanhua.model.domain.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 用户登录：
     */
    public Map login(Map map) {
        String username =  (String)map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");

        //判断账号密码是否为空
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new BusinessException("账号或密码错误为空!");
        }
        //判断验证码是否为空  校验验证码
        if (StringUtils.isEmpty(verificationCode) ||!redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid).equals(verificationCode)){
            throw new BusinessException("验证码错误!");
        }

        //根据用户名查询用户
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(lqw);
        //解密密码
        String s = SecureUtil.md5(password);
        if (admin==null || !s.equals(admin.getPassword())){
            //用户名错误或者密码不一致
            throw new BusinessException("用户名或者密码");
        }
        //通过JWT生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", username);
        claims.put("id", admin.getId());
        String token = JwtUtils.getToken(claims);
        //构造返回值
        Map res = new HashMap();
        res.put("token",token);
        return res;
    }


    /**
     * 获取用户的信息
     */
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);

    }
}
